<template>
  <div class="app-container" ref="appcontainer">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >

      <el-form-item label="资质类型" prop="zizhiTypeId">

        <el-select
          v-model="queryParams.zizhiTypeId"
          placeholder="请选择证书"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="证书名称" prop="enterpriseId">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入证书名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="" size="mini" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-if="false"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :height="tableHeight"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column
        type="selection"
        width="55"
        align="center"
        show-overflow-tooltip
      /> -->
      <el-table-column label="序号" align="center" prop="id" />
      <!-- <el-table-column label="企业名称" align="center" prop="enterpriseName" /> -->
      <el-table-column label="证书名称" align="center" prop="name" />
      <el-table-column
        label="证书编号"
        align="center"
        prop="certificateNumber"
      />
      <el-table-column label="发证日期" align="center" prop="certificateDate">
        <template slot-scope="scope">
          {{ scope.row.certificateDate ? formatDate(scope.row.certificateDate) : '-' }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="资质类型" align="center" prop="zizhiTypeId">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.zizhiTypeId" />
        </template>
      </el-table-column> -->
      <el-table-column label="资质文件" align="center" prop="zizhiFile">
        <template slot-scope="scope">
          <!-- <el-link
            type="primary"
            :href="`${scope.row.zizhiFile}`"
            target="_blank"
            v-show="scope.row.zizhiFile"
            >查看</el-link> -->
          
          <el-link v-for="item in scope.row.zizhiFileArr"  :key="item"
            type="primary"
            :href="item"
            target="_blank"
            >{{getFileName(item)}}</el-link>
          
        </template>
      </el-table-column>
      <el-table-column
        v-if="is_yezhu==0"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资质信息对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="企业名称" prop="enterpriseId">
          <el-select v-model="form.enterpriseId" placeholder="请选择企业">
            <el-option
              v-for="dict in enterpriseList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资质类型" prop="zizhiTypeId">
          <el-select v-model="form.zizhiTypeId" placeholder="请选择资质类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item> -->


        <el-form-item label="证书名称" prop="name">
          <el-input
            v-model="form.name"
            type="text"
            auto-complete="off"
            placeholder="请输入证书名称"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="证书编号" prop="certificateNumber">
          <el-input
            v-model="form.certificateNumber"
            type="text"
            auto-complete="off"
            placeholder="请输入证书编号"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="发证日期" prop="certificateDate">
          <el-date-picker
            v-model="form.certificateDate"
            type="date"
            placeholder="选择日期"
            style="width: 140px"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="有效期至" prop="becomeDate">
          <el-date-picker
            v-model="form.becomeDate"
            type="date"
            placeholder="选择有效期至"
            style="width: 140px"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="资质文件" prop="zizhiFile">
          <fileUpload v-model="form.zizhiFile" />
        </el-form-item>
        
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  exportEnterprise,
  listEnterpriseAll,
} from "@/api/enterprise/enterprise";
import {
  listCertifi,
  addCertifi,
  updateCertifi,
  delCertifi,
  getCertifi,
} from "@/api/certification/certification";
import FileUploadImage from "@/components/FileUploadImage/index.vue";
import Cookies from "js-cookie";

export default {
  name: "Certification",
  components: { FileUploadImage },
  data() {
    return {
      cookietoken: "init",
      // 公共链接
      action: process.env.VUE_APP_BASE_API + "/common/upload",
      // 文件列表
      fileList: [],
      // 企业列表
      enterpriseList: [],
      tableHeight: 0,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业信息表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 企业类型字典
      typeOptions: [],
      // 状态 1=开业，2=停业字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null,
        type: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // enterpriseId: [
        //   { required: true, message: "企业名称不能为空", trigger: "blur" },
        // ],
        // zizhiTypeId: [
        //   { required: true, message: "企业类型不能为空", trigger: "blur" },
        // ],
        zizhiFile: [
          {
            required: true,
            message: "资质文件不能为空",
            trigger: "blur",
          },
        ],
        name: [
          { required: true, message: "证书名称不能为空", trigger: "blur" },
        ],
        certificateNumber: [
          { required: true, message: "证书编号不能为空", trigger: "blur" },
        ],
        certificateDate: [
          { required: true, message: "证书日期不能为空", trigger: "blur" },
        ],
        becomeDate: [
          { required: true, message: "有效期至不能为空", trigger: "blur" },
        ],
        
      },
      roleId: null,
      roles: [],
      enterpriseId: null,
      is_yezhu:0,
    };
  },
  created() {
    //当前用户的信息
    let userInfo = JSON.parse(Cookies.get("userinfo"));
    this.roles = userInfo.roles;
    this.roleId = userInfo.roleId;
    this.enterpriseId = userInfo.enterpriseId;

    //业主
    for(let i=0; i < this.roles.length;i++){
      if(this.roles[i].roleId == 6 || this.roles[i].roleId == 9){
        this.is_yezhu = 1
      }
    }

    this.getList();
    this.calHeight();
    this.getDicts("sy_zizhi_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("gc_enterprise_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getEnterList();
    this.consoleTkent();
  },
  watch: {
    showSearch: "calHeight",
  },
  methods: {
    // 格式化日期
    formatDate(date) {
      const dateObj = new Date(date);
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1;
      const day = dateObj.getDate();
      return `${year}-${month < 10 ? "0" + month : month}-${
        day < 10 ? "0" + day : day
      }`;
    },
    handleSuccess(file) {
      console.log(file);
      // 截取fileName的upload后面的字符
      const uploadIndex = file.fileName.indexOf("upload");
      const result = file.fileName.substring(uploadIndex - 1);
      this.form.zizhiFile = result;
      console.log(this.form);
    },
    consoleTkent() {
      this.cookietoken = getToken();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 获取所有企业列表
    getEnterList() {
      listEnterpriseAll().then((res) => {
        this.enterpriseList = res.data;
      });
    },
    calHeight() {
      this.$nextTick(() => {
        const rect = this.$refs.appcontainer.getBoundingClientRect();
        let height = this.$refs.queryForm.$el.offsetHeight;
        this.tableHeight = rect.height - height - 120;
      });
    },
    /** 查询信息 */
    getList() {
      this.loading = true;
      // 查看路由是否有id参数
      const id = this.$route.query.id;
      if (id) {
        this.queryParams.enterpriseId = id;
      }

      for (let i = 0; i < this.roles.length; i++) {
        if (this.roles[i].roleId == 6) {
          this.queryParams.enterpriseId = this.enterpriseId;
          break;
        }
      }

      listCertifi(this.queryParams).then((response) => {
        let list = response.rows;

        list.forEach(item => {
          let arr = item.zizhiFile.split(",")
          item.zizhiFileArr = arr;
        });

        this.list = list;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        code: null,
        type: null,
        contacts: null,
        mobile: null,
        status: 0,
        createTime: null,
        updateTime: null,
        zizhiFile: null,
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.showSearch = true;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
      },
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资质信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCertifi(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资质信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCertifi(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCertifi(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delCertifi(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有企业信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportEnterprise(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    // 获取文件名称
    getFileName(name) {
      if (name) {
        console.log(name);
        if (name.lastIndexOf("/") > -1) {
          return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
        } else {
          return "";
        }
      } else {
        return "";
      }
    },
  },
};
</script>
